iT邦幫忙

2023 iThome 鐵人賽

DAY 1
0
自我挑戰組

Django系列 第 10

Day10~Django 漫漫長路- 多檔案上傳

  • 分享至 

  • xImage
  •  

大家好,我是Leo
今天我們會延續昨天的上傳檔案,但今天要講解的是上傳多個檔案/images/emoticon/emoticon30.gif
OK~~~ Let's go now!!!


model

如果我們今天想要敲一次API就能達到上傳多個user證照的圖檔,概念圖如下

https://ithelp.ithome.com.tw/upload/images/20221229/20154853yPsnikHwmx.jpg

如果不太清楚model內的function get_file的朋友,可以去看上一篇有介紹,主要是更改檔案存檔的路徑
models/user_certificates_model.py

from django.db import models
from website.models.users_model import Users
import uuid
import os

def get_file(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join(f'users/{instance.user.id}', filename)

class User_Certificates(models.Model):
    id =  models.AutoField(primary_key=True)
    user = models.ForeignKey(Users, on_delete=models.PROTECT, to_field='id', related_name='user_certicicate_users',default=None,blank=True,null=True)
    file_name = models.CharField(max_length=255,null=True)
    file_path = models.FileField(upload_to=get_file,null=True, blank=True, default=None)
    created_at = models.DateTimeField(auto_now_add = True,editable=False)
    deleted_at = models.DateTimeField(null=True)

model/init.py

from .user_certificates_model import *

serializers

這邊file_path將serializer的type改成list,而裡面的子檔案為FieField的型式

  • validated_data 驗證成功,可以通過序列化器對象的獲取數據,獲取的是一個有序的字典類型的數據 data from views request.data的參數。

  • pop的用法,像是移除一個值,我們也可以將移除的值儲存在一個變數內
    也就是說,如果我有一個dict 為{"apple":50,"orange":10,"banana":20}
    如果我今天apple_value = dict.pop("apple") -> dict = {"orange":10,"banana":20}
    而這時候apple_value = 50

serializers/user_certificates_ser.py

from rest_framework import serializers
from website.models import User_Certificates

class UserCertificatesSerializers(serializers.ModelSerializer):
    file_path = serializers.ListField(
        child=serializers.FileField(max_length=100000,
                                    allow_empty_file=True,
                                    use_url=True), write_only=True
    )
    class Meta:
        model = User_Certificates
        fields = ('file_name','file_path','user')

    def create(self, validated_data):
        file_path = validated_data.pop('file_path')
        user = validated_data.pop('user')
        file_name = validated_data.pop('file_name')
        for img in file_path:
            photo = User_Certificates.objects.create(
                user=user,
                file_name = file_name,
                file_path=img
            )
            photo.save()

        return user

serializers/init.py

from .user_certificates_ser import *

views

  • serializer.is_valid 驗證serializer是否有效,如果有值遺漏時,則不會存儲serializer
  • serializer.save() 一定要在serializer.is_valid 驗證之後才可以儲存
  • request.data.get 取得resquest的參數

views/user_certificates.py

from rest_framework import generics,permissions
from rest_framework.response import Response
from website.serializers import UserCertificatesSerializers

class UserCertificatesCreateAPIViews(generics.CreateAPIView):
    permission_classes = (permissions.AllowAny,)
    authentication_classes = []

    def post(self, request, *args):
        serializer = UserCertificatesSerializers(data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response({'success': True,
                             'userId':request.data.get('user'),
                            'message': "certificates created successfully"})
        return Response({'success': False,
                         'userId': request.data.get('user'),
                         'message': "certificates created error"})

views/init.py

from .user_certificates import *

url

urls.py

from website.views import (
    UserCertificatesCreateAPIViews
)

path('api/user/certificates/create', UserCertificatesCreateAPIViews.as_view(), name='api-user-certificates-create')

testing

https://ithelp.ithome.com.tw/upload/images/20221229/20154853Ay9tlcOoqC.jpg

https://ithelp.ithome.com.tw/upload/images/20221229/20154853LOyxQLYNaL.jpg


今天主要是介紹多個檔案的上傳方式,明天我們來介紹縣市鄉鎮的篩選
我們明天見,各位掰掰~~~/images/emoticon/emoticon29.gif


上一篇
Day9~Django 漫漫長路- 我把檔案都上傳到那裡了
下一篇
Day11~Django 漫漫長路-當post 遇上了 filter
系列文
Django30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言